package com.wang.interview;

import java.text.SimpleDateFormat;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.wang.spring.UserInfo2;


/*
  瞬态(Transitent)，持久(Persistent)和分离(Detached)的概念。

临时态  转换:通过new创建的对象为临时态,通过delete方法操作的对象转变为临时态,
		特征:临时态的对象可以被垃圾回收,临时态的对象未进行持久化,未与session关联.
持久态  转换:通过get,load, list, iterate()方法查询到的对象为持久态;通过save, update方法操作的对象转换为持久态	
		特征:持久态对象垃圾回收器不能回收;持久态对象进行了持久化,与session关联,实际上持久化对象
		存在于session缓存中,由session负责管理;持久态对象的数据可以自动更新到数据库中,时机是在调用
		session.flush()执行,而提交事务时会调用session.flush().ts.commit()==>session.flush()+commit.
游离态  转换:通过session的evict,clear,close方法操作的对象会转换为游离态
	    特征:游离态的对象可以被垃圾回收;游离态的对象进行过持久化,但是与session解除了关联.
 

 */
public class HibernateTest {
	
	StandardServiceRegistry registry = null;
	SessionFactory sessionFactory = null;
	Session session = null;
	Transaction transaction = null;
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Before
	public void init() {

		//hibernate4 get factory
//		Configuration configuration = new Configuration();
//		configuration.configure();
//		serviceRegistry = new ServiceRegistryBuilder().applySettings(
//				configuration.getProperties()).buildServiceRegistry();
//		sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		
		
		//hibernate5 get factory
		StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml")
				.build();
		Metadata metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build();
		sessionFactory = metaData.getSessionFactoryBuilder().build();
		session = sessionFactory.openSession();
		transaction = session.getTransaction();
		transaction.begin();

	}

//	@Test
//	public void testSaveUser() {
//		UserInfo2 userInfo = new UserInfo2();
//		userInfo.setUsername("demo02");
//		userInfo.setPassword("123456");
//		userInfo.setUser_Role("admin");
//		userInfo.setEnabled("Y");
//		userInfo.setUserid(1002);
//		session.persist(userInfo);
//	}
	
	@Test
	public void  findUser(){
		UserInfo2 userInfo = (UserInfo2)session.get(UserInfo2.class,"demo01");
		System.out.println(userInfo);
	}

		
	@After
	public void destroy() {
		transaction.commit();
		session.close();
		sessionFactory.close();
		StandardServiceRegistryBuilder.destroy(registry);
	}
	
}
